package org.example.myleet.p387;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class Solution {
    /**
     * 32 ms
     */
//    public int firstUniqChar(String s) {
//        for (int i=0;i<s.length();i++) {
//            char c = s.charAt(i);
//            if (s.indexOf(c) == s.lastIndexOf(c)) {
//                return i;
//            }
//        }
//        return -1;
//    }

    /**
     * 14 ms
     */
    public int firstUniqChar(String s) {
        List<Character> result = new LinkedList<>();
        Map<Character, Integer> charPositionMap = new HashMap<>();
        int[] count = new int[128];
        for (int i=0;i<s.length();i++) {
            Character c = s.charAt(i);
            ++count[c];
            if (count[c] == 1) {
                result.add(c);
                charPositionMap.put(c, i);
            } else if (count[c] == 2) {
                charPositionMap.put(c, -1);
            }
        }
        int position = -1;
        for (Character c : result) {
            if ((position = charPositionMap.get(c)) > -1) {
                return position;
            }
        }
        return position;
    }
}
